/************************************************************************/
/* Resources                                                            */
/************************************************************************/
#include "Resources/sfx/SDLMusic.h"

namespace TD_Resources {

	bool SDLMusic::m_mixerInitialized = false;

	SDLMusic::SDLMusic() : Resource() {
		m_pMusic = NULL;
		m_channel = -1;
	}

	SDLMusic::SDLMusic(const SDLMusic &rhs) : Resource(rhs) {
		
	}

	SDLMusic & SDLMusic::operator=(const SDLMusic &rhs) {
		Resource::operator =(rhs);
		return(*this);
	}

	SDLMusic::SDLMusic(const string &musicName) : Resource(musicName){
		m_pMusic = NULL;
	}

	SDLMusic::~SDLMusic() {
		Mix_HaltMusic();
		Mix_FreeMusic(m_pMusic);
		m_pMusic = NULL;
	}

	bool SDLMusic::loadFile(const string &file) {
		if(m_mixerInitialized == false) {
			initSoundMixer();
		}

		if(m_pMusic != NULL) {
			Mix_FreeMusic(m_pMusic);
			m_pMusic = NULL;
		}

		/* Loads up the music */
		m_pMusic = Mix_LoadMUS(file.c_str());
		if(m_pMusic == NULL) {
			return false;
		}
		return true;

	}

	void SDLMusic::initSoundMixer() {
		
#ifdef _WII
		int audio_rate = 32000;
		Uint16 audio_format = AUDIO_S16; /* 16-bit stereo */
		int audio_channels = 2;
		int audio_buffers = 512;
#elif WIN32
		int audio_rate = 44100;
		Uint16 audio_format = AUDIO_S16; /* 16-bit stereo */
		int audio_channels = 2;
		int audio_buffers = 4096;
#endif
		
		

		if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers) ){
			m_mixerInitialized = false;
			exit(1);
		}

		Mix_VolumeMusic(MIX_MAX_VOLUME);

		m_mixerInitialized = true;

	}

	void SDLMusic::playMusic(bool loopMusic) {
		if(m_mixerInitialized == false) {
			initSoundMixer();
		}

		if(m_pMusic != NULL) {
			if(loopMusic) {
				m_channel = Mix_PlayMusic(m_pMusic, -1);
			} else {
				m_channel = Mix_PlayMusic(m_pMusic, 0);
			}
				
		} 
	}

	
}